package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"novel-sys/cache"
	"novel-sys/model/mysql"

	"novel-sys/goods/goods"
	"novel-sys/goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginRegisterLogic {
	return &LoginRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginRegisterLogic) LoginRegister(in *goods.LoginRegisterRequest) (*goods.LoginRegisterResponse, error) {
	// todo: add your logic here and delete this line
	data := mysql.User{
		Mobile:    in.Mobile,
		Password:  in.Password,
		HeadImage: "https://ts1.tc.mm.bing.net/th/id/OIP-C.JKAOWcVsAT4_-ac9QlmekAAAAA?w=205&h=211&c=8&rs=1&qlt=90&r=0&o=6&cb=ucfimgc1&dpr=1.5&pid=3.1&rm=2",
		NickName:  fmt.Sprintf("用户%v", rand.Intn(9000)),
	}
	var user mysql.User
	if err := user.UserByMobile(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}
	if in.Type == 1 {

		if in.Password != data.Password {
			return nil, errors.New("密码错误")
		}
	}
	if in.Type == 2 {
		get, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Mobile).Result()
		if in.Sms != get {
			return nil, errors.New("验证码错误")
		}
		cache.Rdb.Del(l.ctx, "SendSms"+in.Mobile)
		cache.Rdb.Del(l.ctx, "SendSms1"+in.Mobile)
	}
	if err := data.Register(mysql.DB, in); err != nil {
		return nil, err
	}
	return &goods.LoginRegisterResponse{
		UserId: int64(data.ID),
	}, nil
}
